package com.yonyou.ucf.mdf.app.isvdxq.secondpart.service;

import com.alibaba.fastjson.JSONObject;
import com.yonyou.ucf.mdf.app.isvdxq.ReturnResult.DataResult;
import com.yonyou.ucf.mdf.app.isvdxq.common.ApiYon;
import com.yonyou.ucf.mdf.app.isvdxq.common.DxqConfig;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.RFIDCodeDetail.entity.RfidCodebind;
import com.yonyou.ucf.mdf.app.isvdxq.other.model.AccessTokenResponse;
import com.yonyou.ucf.mdf.app.isvdxq.other.service.BaseService;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.entity.EpcEntity;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.entity.PrelableEntity;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.entity.StorerecordEntity;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.mapper.impl.EpclistMapperImpl;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.mapper.impl.PrelableMapperImpl;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.mapper.impl.StorerecordEntityMapperImpl;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.model.*;
import com.yonyou.ucf.mdf.app.isvdxq.utils.DateUtil;
import com.yonyou.ucf.mdf.app.isvdxq.utils.GenericResponse;
import com.yonyou.ucf.mdf.app.isvdxq.utils.MyTool;
import com.yonyou.ucf.mdf.app.isvdxq.utils.RequestTool;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class EpclistService {
    @Autowired
    BaseService baseService;
    @Autowired
    EpclistMapperImpl epclistMapper;
    @Autowired
    PrelableMapperImpl prelableMapper;
    @Autowired
    StorerecordEntityMapperImpl storerecordentityMapper;

    @Autowired
    EpclistMapperImpl tempEpclistMapper;


    public EpcEntity SelectById(String id) {
        return epclistMapper.selectById(id);
    }

    public EpcEntity SelectByEpc(String epc, String tenantId) {
        return epclistMapper.selectByEpc(epc, tenantId);
    }

    public List<EpcEntity> SelectByEpcs(List<String> strList, String tenantId) {
        return epclistMapper.selectByEpcs(strList, tenantId);
    }

    public List<EpcEntity> SelectByIds(List<String> strList, String tenantId) {
        List<EpcEntity> resList = new ArrayList<>();
        if (strList.size() == 0) return resList;
        return epclistMapper.selectByIds(strList, tenantId);
    }

    public List<EpcEntity> SelectByWIds(List<String> strList, String tenantId) {
        return epclistMapper.selectByWIds(strList, tenantId);
    }

    public List<EpcEntity> SelectByLIds(List<String> strList, String tenantId) {
        return epclistMapper.selectByLIds(strList, tenantId);
    }

    public List<EpcEntity> SelectAll(String tenantId) {
        return epclistMapper.selectAll(tenantId);
    }

    public Integer InsertEntity(EpcEntity entity) {
        return epclistMapper.insert(entity);
    }

    public Integer UpdateEntity(EpcEntity entity) {
        return epclistMapper.updateByPrimaryKey(entity);
    }

    public Integer DeleteById(String id) {
        return epclistMapper.deleteByPrimaryKey(id);
    }

    public Integer EditStatus(List<String> ids, Integer status, String userId, String tenantId) throws Exception {
        return epclistMapper.editStatus(ids, userId, String.valueOf(status), tenantId);
    }

    //新增并更新
    public Integer InsertBatch(List<EpcEntity> list) {
        if (list.size() == 0) return 0;
        long start = System.currentTimeMillis();
        int res = epclistMapper.insertBatch(list);
        long end = System.currentTimeMillis();
        System.out.println("---------------" + (start - end) + "---------------");
        return res;
    }

    @Transactional(rollbackFor = Exception.class)
    public Integer MergeEpc(EpcEntity entity, List<String> epcs, String tenantId) {
        List<EpcEntity> epcEntities = tempEpclistMapper.selectByEpcs(epcs, tenantId);
        if (epcEntities.size() > 0) {
            for (EpcEntity item : epcEntities) {
                item.setPk_temp("mergeepc");
            }
            tempEpclistMapper.insertBatchHistory(epcEntities);
        }
        int rInt = tempEpclistMapper.updateByPrimaryKey(entity);
        epcs.remove(entity.getRfid_code());
        if (epcs.size() > 0) {
            int rInt_entity = tempEpclistMapper.deleteByEpcs(epcs, tenantId);
        }
        return rInt;
    }

    @Transactional(rollbackFor = Exception.class)
    public int SplitEpc(EpcEntity entity, EpcEntity entityNew, String tenantId) {
        EpcEntity epcEntity = tempEpclistMapper.selectById(entity.getId());
        if (epcEntity != null) {
            epcEntity.setPk_temp("splitepc");
            List<EpcEntity> dataHistory = new ArrayList<>();
            dataHistory.add(epcEntity);
            tempEpclistMapper.insertBatchHistory(dataHistory);
        }
        //更新入库记录，补入库记录
        List<StorerecordEntity> editEntity = new ArrayList<>();
        StorerecordEntity storerecordEntity = storerecordentityMapper.selectListByEpcId(entity.getId(), String.valueOf(DxqConfig.TypeIn), tenantId);
        if (storerecordEntity != null) {
            StorerecordEntity recordNew = MyTool.convertBean2Bean(storerecordEntity, StorerecordEntity.class);
            recordNew.setId(MyTool.getRandomId());
            recordNew.setRfidcode(entityNew.getRfid_code());
            recordNew.setRfidcodeId(entityNew.getId());
            recordNew.setF_stock_count(entityNew.getF_stock_count());
            storerecordEntity.setF_stock_count(entity.getF_stock_count());
            storerecordentityMapper.insert(recordNew);
            editEntity.add(storerecordEntity);
        }
        if (editEntity.size() > 0)
            storerecordentityMapper.insertBatch(editEntity);
        //更新库存EPC
        int rInt = tempEpclistMapper.updateByPrimaryKey(entity);
        int rInt_new = tempEpclistMapper.insert(entityNew);
        return rInt;
    }

    /**
     * 组装入库数据
     *
     * @param orderid
     * @param orderDetailId
     * @param tenantId
     * @return
     * @throws IOException
     */
    public DataResult GetOrderDH(String orderid, String orderDetailId, String tenantId) throws IOException {
        DataResult result = new DataResult(0, "单据数据获取异常");
        String gatewayUrl = baseService.buildBusinessUrl(tenantId);
        AccessTokenResponse MyToken = baseService.getAccessToken3(tenantId);
        String token = MyToken.getAccessToken();
        String requrl = gatewayUrl + ApiYon.getArrivalOrderDetail + "?access_token=" + token;
        Map<String, String> params = new HashMap<>();
        // 除签名外的其他参数
        params.put("id", orderid);
        String resString = RequestTool.doGet(requrl, params);
        GenericResponse response = JSONObject.parseObject(resString, GenericResponse.class);

//        GenericResponse<OrderDetailDHBean> response = RequestTool.getBean(resString,
//                new TypeReference<GenericResponse<OrderDetailDHBean>>() {
//                });
        if (response.getCode().equals("200")) {
            OrderDetailDHBean tempBean = JSONObject.parseObject(JSONObject.toJSONString(response.getData()),
                    OrderDetailDHBean.class);
//            OrderDetailDHBean tempBean = response.getData();

            result = new DataResult(1, "操作成功");
            result.setData(tempBean);
            return result;
        }
        result.setMessage(response.getMessage());
        return result;
    }

    // 组装提交数据
    public DataResult MakeDataForDHSumit(List<PrelableEntity> datalist, OrderDetailDHBean tempBean,
                                         String orderDetailId, String tenantId, String batchno_dxq) {
        DataResult result = new DataResult(0, "单据数据获取异常");
        if (tempBean == null) {
            return result;
        }
        if (tempBean.getArrivalOrders() == null || tempBean.getArrivalOrders().size() == 0) {
            result.setMessage("订单到货异常");
            return result;
        } else if (!tempBean.getStatus().equals("1")) {
            result.setMessage("订单未审核");
            return result;
        }
        String orderid = tempBean.getId();
        List<YonyouInParamBean.ChildInfo> childList = new ArrayList<>();
        // 到货物料信息
        List<OrderDetailDHBean.DetailDHItem> itemEntityList = tempBean.getArrivalOrders().stream()
                .filter(it -> it.getId().equals(orderDetailId))
                .collect(Collectors.toList());
        if (itemEntityList == null || itemEntityList.size() == 0) return result;
        OrderDetailDHBean.DetailDHItem itemEntity = itemEntityList.get(0);
        if (itemEntity == null) return result;

        String warehouseId = itemEntity.getWarehouse();
        double orMoney = Double.parseDouble(itemEntity.getOriMoney());
        double oriUnitPrice = Double.parseDouble(itemEntity.getOriUnitPrice());
        boolean isBatchManage = itemEntity.isBatchManage(); //是否批次管理
        boolean isExpiryDateManage = itemEntity.isExpiryDateManage();//是否效期管理：true or false

        int countEPC = 0;
        for (PrelableEntity item : datalist) {
            YonyouInParamBean.ChildInfo childInfo = new YonyouInParamBean.ChildInfo();
            childInfo.setMakeRuleCode("pu_arrivalorder"); //到货入库
            childInfo.setSourceid(orderid);
            childInfo.setSourceautoid(orderDetailId);
            if (isBatchManage && StringUtils.isEmpty(item.getBatchno())) {
                result.setMessage("批次管理异常");
                return result;
            } else if (isExpiryDateManage && StringUtils.isEmpty(item.getProductdate())) {
                result.setMessage("有效期管理异常");
                return result;
            }
            childInfo.setBatchno(item.getBatchno());
            childInfo.setProducedate(item.getProductdate());
            Double qty = item.getStockNum();
            childInfo.setQty(qty); //实收数量
            childInfo.setContactsQuantity(qty); //应收数量
            childInfo.setOriMoney(oriUnitPrice * qty); //原币无税金额=原币无税单价*数量
            childInfo.set_status("Insert");
            childInfo.setResubmitCheckKey(batchno_dxq);
            childInfo.setMemo(MyTool.makeMemoForDetail("dxq_storerecord", "1", item.getEpccode()));//用友数据绑定
            // 增加条码明细上传 【1】商品数量与序列号数量不一致，请检查
//            childInfo.setIsSerialNoManage(true);
//            List<YonyouInParamBean.SnInfo> purInRecordsSNs = new ArrayList<>();
//            YonyouInParamBean.SnInfo snInfo = new YonyouInParamBean.SnInfo();
//            snInfo.set_status("Insert");
//            snInfo.setSn(item.getEpccode());
//            purInRecordsSNs.add(snInfo);
//            childInfo.setPurInRecordsSNs(purInRecordsSNs);

            childList.add(childInfo);
            countEPC++;
        }

        YonyouInParamBean entity = new YonyouInParamBean();
        entity.setResubmitCheckKey(MyTool.GenerateTime());
        entity.setMergeSourceData(true);
        entity.setNeedCalcLines(true);
        entity.setCalcLinesKey("oriMoney"); //表体行计算依据，不传或传入null时默认原币无税金额（oriMoney）
        entity.setVouchdate(MyTool.GenerateTime("yyyy-MM-dd HH:mm:ss"));
        entity.setBustype(DxqConfig.transtype_in); //普通采购
        entity.setWarehouse(warehouseId);
        entity.set_status("Insert");
        entity.setPurInRecords(childList);
        entity.setMemo(MyTool.makeMemo(batchno_dxq, countEPC));//别名

        result = new DataResult(1, "操作成功");
        result.setData(entity);
        return result;
    }

    /**
     * 用友 到货单-普通采购入库提交
     *
     * @param model
     * @param tenantId
     * @return
     * @throws IOException
     */
    public DataResult OrderDHSubmit(YonyouInParamBean model, String tenantId) throws IOException {
        Map<String, YonyouInParamBean> params = new HashMap<>();
        params.put("data", model);

        DataResult result = new DataResult(0, "数据提交异常");
        String gatewayUrl = baseService.buildBusinessUrl(tenantId);
        AccessTokenResponse MyToken = baseService.getAccessToken3(tenantId);
        String token = MyToken.getAccessToken();
        String requrl = gatewayUrl + ApiYon.purInSubmit + "?access_token=" + token;
        System.out.println("[用友 到货单-普通采购入库提交]" + requrl);
        System.out.println(JSONObject.toJSONString(params));
        String resString = RequestTool.doPost(requrl, JSONObject.toJSONString(params));
        System.out.println("[接口回执]" + resString);

        GenericResponse response = JSONObject.parseObject(resString, GenericResponse.class);
        if (response.getCode().equals("200")) {
            result = new DataResult(1, "操作成功");
            result.setData(response.getData());
            return result;
        }
        result.setMessage(response.getMessage());
        return result;
    }

    /**
     * PC发签 本地入库回写 用友入库回写
     *
     * @param prelableList
     * @param model
     * @param tenantId
     * @param modifier
     * @param batch_no
     * @param ordertype
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public DataResult SubmitEpclistCallback(List<PrelableEntity> prelableList, YonyouInReturnBean model,
                                            String tenantId, String modifier, String batch_no, String ordertype) throws Exception {
        DataResult result = new DataResult(0, "数据提交异常");
        if (prelableList == null || prelableList.size() == 0) return result;
        try {
            String orderid = prelableList.get(0).getOrderid();
            String orderDetailId = prelableList.get(0).getOrderdetailid();
            //本次操作EPC数据数组
            List<String> epcs = prelableList.stream().map(it -> it.getEpccode()).distinct().collect(Collectors.toList());
            List<EpcEntity> epcEntityList = epclistMapper.selectByEpcs(epcs, tenantId);
            if (epcEntityList == null || epcEntityList.size() == 0) return result;
            // 验证本地批次
            List<String> epcIds = epcEntityList.stream().map(it -> it.getId()).distinct().collect(Collectors.toList());
            List<StorerecordEntity> list_record = storerecordentityMapper.selectListByEpcIds(epcIds, ordertype,
                    tenantId);

            //本地提交批次 同一个物资多条入库记录
            List<YonyouInReturnBean.PurInRecords> list_detail = model.getPurInRecords().stream()
                    .sorted(Comparator.comparing(YonyouInReturnBean.PurInRecords::getRowno))
                    .collect(Collectors.toList());
            if (list_detail == null || list_detail.size() == 0) {
                result.setMessage("用友数据异常! 单号:" + model.getId() + ",批次号:" + batch_no);
                return result;
            }
            YonyouInReturnBean.PurInRecords tempEntity = list_detail.get(0);
            String sourceautoid = tempEntity.getSourceautoid();
            String sourceid = tempEntity.getSourceid();
            //验证请求数据 是同一单据
            if (!sourceautoid.equals(orderDetailId) || !sourceid.equals(orderid)) {
                result.setMessage("用友数据异常! 单号:" + model.getId() + ",批次号:" + batch_no +
                        "请求单号：" + orderid + "|" + orderDetailId);
                return result;
            }
            String source = tempEntity.getSource();
            String firstsource = tempEntity.getFirstsource();
            String firstsourceautoid = tempEntity.getFirstsourceautoid();
            String firstsourceid = tempEntity.getFirstsourceid();
            String upcode = tempEntity.getUpcode();
            String firstupcode = tempEntity.getFirstupcode();
            //私有方案
            String poid = model.getId();
            String podetailid = tempEntity.getId();
            String pocode = model.getCode();
            //本地库存与用友库存绑定关系
            String stockUnitId = "";
            String stockUnitCode = "";
            String stockUnitName = "";
            for (EpcEntity item : epcEntityList) {
                List<YonyouInReturnBean.PurInRecords> entityList = list_detail.stream()
                        .filter(it -> it.getSourceautoid().equals(orderDetailId)).collect(Collectors.toList());
                if (!StringUtils.isEmpty(item.getBatchno())) {
                    entityList = entityList.stream()
                            .filter(it -> it.getBatchno() != null && it.getBatchno().equals(item.getBatchno()))
                            .collect(Collectors.toList());
                }
                // todo 有效期回写验证 正常应该验证到期时间
                if (!StringUtils.isEmpty(item.getInvalidDate())) {
                    Date tempDate = DateUtil.str2Date(item.getInvalidDate());
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    String productDate = sdf.format(tempDate);
                    entityList = entityList.stream()
                            .filter(it -> it.getInvaliddate() != null && it.getInvaliddate().startsWith(productDate))
                            .collect(Collectors.toList());
                }
                YonyouInReturnBean.PurInRecords entity = entityList.stream()
                        .findFirst().orElse(null);
                if (entity == null) {
                    result.setMessage("远程数据批次或有效期过滤异常");
                    return result;
                }
                stockUnitId = entity.getStockUnitId();
                stockUnitCode = entity.getStockUnit_code();
                stockUnitName = entity.getStockUnit_name();
                item.setInvalidDate(entity.getInvaliddate());
                item.setStockUnitId(entity.getStockUnitId());
                item.setStock_unit_name(entity.getStockUnit_name());
                item.setModifier(modifier);
                item.setBatch_no(batch_no);
            }

            //生成批次号
            String picicode = MyTool.GenerateBatchnoDXQ(ordertype);
            // 回写库存
            tempEpclistMapper.updateByPrimaryKeys(epcEntityList, modifier, tenantId);
            // 回写storerecord
            for (StorerecordEntity item : list_record) {
                EpcEntity entity = epcEntityList.stream().filter(it -> it.getId().equals(item.getRfidcodeId()))
                        .findAny().orElse(null);
                if (entity == null) {
                    result.setMessage("本地数据过滤异常");
                    return result;
                }
                item.setOrderid(orderid);
                item.setOrderdetailid(orderDetailId);
                item.setSource(source);
                item.setFirstsource(firstsource);
                item.setFirstsourceautoid(firstsourceautoid);
                item.setFirstsourceid(firstsourceid);
                item.setUpcode(upcode);
                item.setFirstupcode(firstupcode);
                item.setPoid(poid);
                item.setPodetailid(podetailid);
                item.setPocode(pocode);
                item.setModifier(modifier);
                item.setStockUnitId(stockUnitId);
                item.setStock_unit_id(stockUnitId);
                item.setStock_unit_name(stockUnitName);
                item.setStock_unit_code(stockUnitCode);
                item.setBatch_no(batch_no); // 用友提交成功回写批次
                item.setEpc_status(0); //未上架
                if (!StringUtils.isEmpty(entity.getProductDate()))
                    item.setProductDate(entity.getProductDate());
                if (!StringUtils.isEmpty(entity.getInvalidDate()))
                    item.setInvalidDate(entity.getInvalidDate());
            }
            storerecordentityMapper.insertBatch(list_record);

            result = new DataResult(1, "操作成功");
        } catch (Exception ex) {
            result.setMessage(ex.getMessage());
        }
        return result;
    }

    public static EpcEntity MakeEntityForPad(RfidCodebind item) {
        String tenantId = item.getTenant_id();
        String modifier = item.getModifier();

        EpcEntity epcEntity = new EpcEntity();
        epcEntity.setModifier(modifier);
        epcEntity.setYtenant_id(tenantId);
        epcEntity.setId(MyTool.getRandomId());
        epcEntity.setRfid_code(item.getRfid_code());
        epcEntity.setRfid_status(item.getRfid_status());
        epcEntity.setEpc_tid(item.getEpc_tid());
        epcEntity.setF_stock_count(item.getF_stock_count());
        epcEntity.setF_move_count(0.0d);
        epcEntity.setF_out_count(0.0d);
        epcEntity.setBatchno(item.getBatchno());
        epcEntity.setCreate_time(MyTool.GenerateTime());
        epcEntity.setCreator(modifier);
        epcEntity.setModify_time(MyTool.GenerateTime());
        epcEntity.setModifier(modifier);
        //物料和仓库信息
        epcEntity.setWarehouse_id(item.getWarehouse_id());
        epcEntity.setWarehouse_code(item.getWarehouse_code());
        epcEntity.setLocation_id(item.getLocationId());
        epcEntity.setShelf_id(item.getShelfId());
        epcEntity.setProduct_id(item.getProduct_id());
        epcEntity.setProduct_name(item.getProduct_name());
        epcEntity.setProduct_sku_id(item.getProduct_sku_id());
        epcEntity.setProduct_sku_name(item.getProduct_sku_name());
        epcEntity.setUnitId(item.getUnitId());
        epcEntity.setUnit_name(item.getUnit_name());
        //回写
        epcEntity.setStockUnitId(item.getStockUnitId());
        epcEntity.setStock_unit_name(item.getStock_unit_name());
        epcEntity.setProductDate(null);
        epcEntity.setInvalidDate(null);
        epcEntity.setPickuser("");
        if (!StringUtils.isEmpty(item.getProductDate()))
            epcEntity.setProductDate(item.getProductDate());
        if (!StringUtils.isEmpty(item.getInvalidDate()))
            epcEntity.setInvalidDate(item.getInvalidDate());

        return epcEntity;
    }

    /**
     * 入库发签
     * 必须数据：epc,count,batchno,skuid,proid,warehouseId,unitId
     * 无货位、无货架
     *
     * @param item
     * @param tenantId
     * @param modifier
     * @return
     */
    public static EpcEntity MakeEntityForPC(PrelableEntity item, String tenantId, String modifier) {
        EpcEntity epcEntity = new EpcEntity();
        epcEntity.setModifier(modifier);
        epcEntity.setYtenant_id(tenantId);
        epcEntity.setId(MyTool.getRandomId());
        epcEntity.setRfid_code(item.getEpccode());
        epcEntity.setRfid_status(item.getStatus());
        epcEntity.setEpc_tid(item.getEpc_tid());
        epcEntity.setF_stock_count(item.getStockNum());
        epcEntity.setF_move_count(0.0d);
        epcEntity.setF_out_count(0.0d);
        epcEntity.setBatchno(item.getBatchno());
        epcEntity.setCreate_time(MyTool.GenerateTime());
        epcEntity.setCreator(modifier);
        epcEntity.setModify_time(MyTool.GenerateTime());
        epcEntity.setModifier(modifier);
        //物料和仓库信息
        epcEntity.setWarehouse_id(item.getWarehouseId());
        epcEntity.setWarehouse_code(item.getWarehousecode());
        epcEntity.setProduct_id(item.getProductId());
        epcEntity.setProduct_name(item.getProductname());
        epcEntity.setProduct_sku_id(item.getProductskuId());
        epcEntity.setProduct_sku_name(item.getProductskuname());
        epcEntity.setUnitId(item.getUnitId());
        epcEntity.setUnit_name(item.getUnitname());
        //回写
        epcEntity.setStockUnitId("");
        epcEntity.setStock_unit_name("");
        if (!StringUtils.isEmpty(item.getProductdate()))
            epcEntity.setProductDate(item.getProductdate());
        if (!StringUtils.isEmpty(item.getInvaliddate()))
            epcEntity.setInvalidDate(item.getInvaliddate());

        return epcEntity;
    }

    // 本地批量入库 多次提交不影响 PC发签入库
    public DataResult SubmitEpclist(List<PrelableEntity> prelableList, String tenantId, String userId,
                                    int sourcetype, String batchNum) {
        DataResult result = new DataResult(0, "数据提交异常");
        if (prelableList == null || prelableList.size() == 0) return result;

        //组装数据
        List<EpcEntity> list_epc = new ArrayList<>();
        List<StorerecordEntity> list_storerecord = new ArrayList<>();

        for (PrelableEntity item : prelableList) {
            EpcEntity epcEntity = MakeEntityForPC(item, tenantId, userId);
            if (StringUtils.isEmpty(epcEntity.getProduct_id())) {
                result.setMessage("物料Id不能为空");
                return result;
            } else if (StringUtils.isEmpty(epcEntity.getProduct_sku_id())) {
                result.setMessage("物料SKUId不能为空");
                return result;
            } else if (epcEntity.getF_stock_count() == null || epcEntity.getF_stock_count() == 0) {
                result.setMessage("物料数量异常");
                return result;
            }
            epcEntity.setBatch_no(batchNum);
            list_epc.add(epcEntity);
            //记录
            StorerecordEntity storerecordEntity = StorerecordService.MakeEntityForPC(item, epcEntity, batchNum,
                    tenantId, userId, sourcetype);
            list_storerecord.add(storerecordEntity);
        }

        //事务处理
        if (list_epc.size() > 0 && list_storerecord.size() > 0) {
            // 写入库存
            tempEpclistMapper.insertBatch(list_epc);
            // 写入记录storerecord
            storerecordentityMapper.insertBatch(list_storerecord);
            List<String> epcs = list_epc.stream().map(it -> it.getRfid_code()).distinct().collect(Collectors.toList());
        }

        result = new DataResult(1, "操作成功");
        return result;
    }

    // 入库失败回退
    @Transactional(rollbackFor = Exception.class)
    public boolean DeleteInsertEntityListByOrderId(List<String> epcsDel, String orderid, String tenant_id) {
        List<StorerecordEntity> list_storerecord = storerecordentityMapper.selectByOrderidAndEpcs(orderid, epcsDel,
                tenant_id);
        List<String> ids_storerecord = list_storerecord.stream()
                .map(it -> it.getId()).distinct().collect(Collectors.toList());
        List<String> ids_epc = list_storerecord.stream()
                .map(it -> it.getRfidcodeId()).distinct().collect(Collectors.toList());
        //事务处理
        // 写入库存
        if (ids_epc.size() > 0) {
            List<EpcEntity> epcEntities = tempEpclistMapper.selectByIds(ids_epc, tenant_id);
            if (epcEntities.size() > 0) {
                for (EpcEntity item : epcEntities) {
                    item.setPk_temp("pcinback");
                }
                tempEpclistMapper.insertBatchHistory(epcEntities);
            }
            tempEpclistMapper.deleteByIds(ids_epc, tenant_id);
        }
        // 写入记录storerecord
        if (ids_storerecord.size() > 0)
            storerecordentityMapper.deleteByIds(ids_storerecord, tenant_id);

        return true;
    }

    public List<EpcEntity> SelectPage(String tenantId, int m, int n) {
        return epclistMapper.selectPage(tenantId, m, n);
    }

    public List<ReactEpcpageEntity> SelectPageForReact(String tenantId, int m, int n, ReactEpcpageParam entity) {
        return epclistMapper.selectPageForReact(tenantId, m, n, entity);
    }

    public int SelectPageForReactCount(String tenantId, ReactEpcpageParam entity) {
        return epclistMapper.selectPageForReactCount(tenantId, entity);
    }

    /**
     * 物料上架
     *
     * @param entityList
     * @param tenant_id
     * @return
     * @throws Exception
     */
    public int EditForShangjia(List<EpcEntity> entityList, String tenant_id) throws Exception {
        return epclistMapper.editForShangjia(entityList, tenant_id);
    }
}
